package com.github.glomadrian.roadrunner;

import com.github.glomadrian.roadrunner.path.PathContainer;
import com.github.glomadrian.roadrunner.svg.ConstrainedSvgPathParser;
import com.github.glomadrian.roadrunner.svg.SvgPathParser;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Path;
import ohos.agp.render.PathMeasure;
import ohos.app.Context;

import java.text.ParseException;

/**
 * @author Adrián García Lomas
 */
public abstract class RoadRunner extends Component {
    private SvgPathParser svgPathParser;

    /**
     * RoadRunner
     *
     * @param context
     */
    public RoadRunner(Context context) {
        super(context);
    }

    /**
     * RoadRunner
     *
     * @param context
     * @param attrs
     */
    public RoadRunner(Context context, AttrSet attrs) {
        super(context, attrs);
    }

    /**
     * RoadRunner
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public RoadRunner(Context context, AttrSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * buildPathData
     *
     * @param viewWidth
     * @param viewHeight
     * @param pathData
     * @param originalWidth
     * @param originalHeight
     * @return pathContainer
     * @throws ParseException
     */
    protected PathContainer buildPathData(int viewWidth, int viewHeight, String pathData,
        int originalWidth, int originalHeight) throws ParseException {
        Path path = parsePath(pathData, originalHeight, originalWidth, viewHeight, viewWidth);
        PathContainer pathContainer = new PathContainer();
        pathContainer.path = path;
        pathContainer.length = getPathLength(path);
        return pathContainer;
    }

    private Path parsePath(String data, int originalHeight, int originalWidth, int viewHeight,
        int viewWidth) throws ParseException {
        svgPathParser =
            new ConstrainedSvgPathParser.Builder().originalWidth(originalWidth)
                .originalHeight(originalHeight)
                .viewHeight(viewHeight)
                .viewWidth(viewWidth)
                .build();
        return svgPathParser.parsePath(data);
    }

    private float getPathLength(Path path) {
        float pathLength = 0;
        PathMeasure pm = new PathMeasure(path, true);
        pathLength = Math.max(pathLength, pm.getLength());
        /* while (true) {
          //!pm.nextContour() 暂未找到替换api
          if (!pm.nextContour()) {
            break;
          }
        }*/
        return pathLength;
    }

    abstract void setColor(int color);
}
